<template>
  <section class="component config-base">
    <el-card header="规则基本信息">
      <el-form ref="form" :rules="rules" :model="model" inline label-width="120px">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="model.name" :max-length="50" placeholder="请输入策略名称" :disabled="isDisabled"></el-input>
        </el-form-item>
        <el-form-item label="策略类型" prop="strategyType">
          <el-select v-model="model.strategyType" placeholder="请选择" clearable :disabled="isDisabled">
            <el-option v-for="{ code, name } in $dict.getDictData('StrategyType')" :key="code" :label="name" :value="code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="commonState">
          <el-select v-model="model.commonState" placeholder="请选择" clearable :disabled="isDisabled">
            <el-option v-for="{ code, name } in $dict.getDictData('CommonState')" :key="code" :label="name" :value="code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="model.priority" placeholder="请选择" :disabled="isDisabled">
            <el-option v-for="code in priorityList" :key="code" :label="code" :value="code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div slot="header" class="row between-span">
        <span>设置获取数据规则</span>
        <el-button @click="addNewConfigLine" :disabled="isDisabled">增加</el-button>
      </div>
      <expression-base v-model="strategyDataSet" :isDisabled="isDisabled"></expression-base>
    </el-card>

  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Model } from "vue-property-decorator";
import ExpressionBase from "./expression-base.vue";
import { IstrategyInfo } from "./strategy-helper.config"
import { Form } from "element-ui"
import { ValidatorService } from "~/utils/validator.service";

@Component({
  components: {
    ExpressionBase
  }
})
export default class ConfigBase extends Vue {

  @Model("base-change", {
    required: true,
    type: Object
  })
  private model: any
  @Prop()
  private isDisabled:any
  private priorityList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  private get strategyDataSet() {
    if(!this.model.formulaJson) return []
    return JSON.parse(this.model.formulaJson) as IstrategyInfo[]
  }

  private set strategyDataSet(value) {
    this.model.formulaJson = JSON.stringify(value)
  }

  private rules = {
    name: { required: true, message: "请输入策略名称" },
    strategyType: { required: true, message: "请选择策略类型" },
    commonState: { required: true, message: "请选择策略状态" }
  }

  /**
   * 验证基础配置数据
   */
  public validate() {
    const form = this.$refs.form as Form
    return Promise.all([form.validate(), this.validateExpression(), this.validateBreaketComplete()])
      .then(() => this.emitBaseChange(this.model))
      .catch(() => Promise.reject('config-base'))
  }

  @Emit('base-change')
  private emitBaseChange(v) { }

  /**
   * 验证数据是否完整
   */
  private validateExpression() {
    const rules = {
      relation: { required: true, message: "请选择链接关系符" },
      variable: { required: true, message: "请选择字段" },
      symbol: { required: true, message: "请选择操作符" },
      value: { required: true, message: "缺少期望值" }
    }
    const results = this.strategyDataSet.map(v => ValidatorService.validate(v, rules))
    return Promise.all(results)
      .then(() => true)
      .catch(({ errors }) => {
        if (errors.length) this.$message(errors[0].message)
        return Promise.reject(false)
      })
  }

  /**
   * 验证连接符是否完整
   */
  private validateBreaketComplete() {
    if (!this.strategyDataSet.length) {
      this.$message('请配置数据规则')
      return Promise.reject('Error')
    }
    const result = this.strategyDataSet.reduce((s, c: IstrategyInfo) => {
      if (c.leftBracket === '(') s += 1
      if (c.leftBracket === '((') s += 2
      if (c.rightBracket === ')') s -= 1
      if (c.rightBracket === '))') s -= 2
      return s
    }, 0)

    if (result === 0) {
      return Promise.resolve(true)
    } else {
      const message = result > 0 ? '缺少右括号 ）' : '缺少左括号（'
      this.$message(message)
      return Promise.reject('Error')
    }
  }


  private addNewConfigLine() {
    let addFlag = true;
    if (this.strategyDataSet.length) {
      const lastLine = this.strategyDataSet[this.strategyDataSet.length - 1]
      addFlag = !!lastLine.relation
    }
    if (addFlag) {
      this.strategyDataSet.push({
        relation: "",
        variable: "",
        symbol: "",
        leftBracket: "",
        rightBracket: "",
        value: ""
      })
    } else {
      this.$message.warning("请完善数据规则")
    }
  }

  /**
   * 重置
   */
  private reset() {
    const form: any = this.$refs["form"];
    form.resetFields();
  }

}
</script>

<style lang="less" scoped>
</style>
